//% color="#1E90FF" iconWidth=50 iconHeight=40
namespace SiliconflowAPI4K10 {

    //% block="初始化 API密钥:[API] 模型:[MODEL] 温度:[TEMPERATURE]" blockType="command"
    //% API.shadow="string" API.defl="sk-mzemkwzqqimnjaerpibrijplnfrjxnksslryxqwstgldammz"
    //% MODEL.shadow="dropdown" MODEL.options="MODEL"

    //% TEMPERATURE.shadow="dropdown" TEMPERATURE.options="TEMPERATURE"

    export function initializedeepseekAI(parameter: any, block: any) {
        let api = parameter.API.code;
        let model = parameter.MODEL.code;
        let temperature = parameter.TEMPERATURE.code;
        Generator.addInclude('HTTPClient', '#include <HTTPClient.h>');
        Generator.addInclude('ArduinoJson', '#include <ArduinoJsonV7.h>');
        Generator.addInclude('WiFiClientSecure', '#include <WiFiClientSecure.h>');
                     
        Generator.addObject(`api_url`, `String`, `api_url = "https://api.siliconflow.cn/v1/chat/completions"`);
        Generator.addObject(`api_key`, `String`, `api_key=${api}`);
        Generator.addObject(`model`, `String`, `model="${model}"`);

        Generator.addObject(`temperature`, `float`, `temperature=${temperature};`);
     

    }
    //% block="设置模型角色:[deepseek_role] " blockType="command"
    //% deepseek_role.shadow="string" deepseek_role.defl="你擅长简洁的中文对话。"

    export function initializedeepseekRole(parameter: any, block: any) {
        let deepseek_role = parameter.deepseek_role.code;
        Generator.addObject(`deepseek_role`, `String`,`deepseek_role =${deepseek_role};`);
    }
 //% block="发送消息 [MESSAGE]重试次数:[maxMessages]字数:[chatsize]" blockType="command"
 //% MESSAGE.shadow="string" MESSAGE.defl="模仿李白写首的诗，结合张家川的历史典故美景。"
 //% maxMessages.shadow="range"   maxMessages.params.min=3   maxMessages.params.max=10    maxMessages.defl=5
//% chatsize.shadow="range"   chatsize.params.min=50    chatsize.params.max=300    chatsize.defl=150

export function sendMessage(parameter: any, block: any) {
    let chatsize = parameter.chatsize.code;
    let userMessage = parameter.MESSAGE.code;
    let maxMessages = parameter.maxMessages.code;

  Generator.addCode(`
	// 构建 JSON 请求体
	DynamicJsonDocument doc(4096);
	doc["model"] = model;
	doc["stream"] = false;
	doc["max_tokens"] = 300;
	doc["temperature"] = temperature;
	doc["top_p"] = 0.7;
	doc["top_k"] = 50;
	doc["frequency_penalty"] = 0.5;
	
	JsonArray messages = doc.createNestedArray("messages");
	JsonObject systemMsg = messages.createNestedObject();
	systemMsg["role"] = "system";
	systemMsg["content"] = deepseek_role;
	
	JsonObject userMsg = messages.createNestedObject();
	userMsg["role"] = "user";
	userMsg["content"] = String(${userMessage})+String(";限制字数不能超过${chatsize}字");
	
	String payload;
	serializeJson(doc, payload);
	
	Serial.println("请求负载: " + payload);
	
	String content = "未能获取到内容，请检查网络连接或接口状态。";
	
	// 创建安全客户端
	WiFiClientSecure secureClient;
	secureClient.setInsecure(); // 跳过 SSL 证书校验
	
	// 增加缓冲区大小和超时时间
	secureClient.setTimeout(15000); // 15秒超时
	
	HTTPClient http;
	http.setTimeout(15000); // 增加超时时间到15秒
	
  http.begin(secureClient, api_url);
	api_key = String("Bearer " )+ String(api_key);
	// 设置请求头
	http.addHeader("Content-Type", "application/json");
	http.addHeader("Authorization", api_key);
	http.addHeader("User-Agent", "ESP32-HTTPClient/1.0");
	http.addHeader("Connection", "close");
	
	int retry = ${maxMessages};
	bool success = false;
	
	while (retry-- > 0 && !success) {
		Serial.println("尝试发送请求，剩余重试次数: " + String(retry + 1));

		
		int httpCode = http.POST(payload);
		Serial.print("HTTP 响应码: ");
		Serial.println(httpCode);
		
		if (httpCode == HTTP_CODE_OK) {
			String response = http.getString();
			Serial.println("API响应成功，响应长度: " + String(response.length()));
			Serial.println("返回内容:");
			Serial.println(response);
			
			// 解析JSON响应
			DynamicJsonDocument resDoc(4096);
			DeserializationError error = deserializeJson(resDoc, response);
			
			if (!error) {
				if (resDoc.containsKey("choices") && resDoc["choices"].size() > 0) {
					content = resDoc["choices"][0]["message"]["content"].as<String>();
					success = true;
					Serial.println("成功获取内容: " + content);
				} else {
					content = "API响应格式错误";
					Serial.println("API响应中没有找到choices字段");
				}
			} else {
				content = String("JSON 解析失败: ") + error.c_str();
				Serial.println(content);
			}
			break;
		} else {
			// 根据错误码提供更详细的错误信息
			
			Serial.println("请求失败" );
			
			if (retry > 0) {
				Serial.println("等待后重试...");
				delay(2000); // 增加重试间隔
			}
		}
	}
	
	http.end();
	secureClient.stop();
   
  `);

}

    //% block="返回结果" blockType="reporter"
    export function reMessage(parameter: any, block: any) {
        Generator.addCode(`content`);
    }
}
